/*
 * Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
 */
package src.com.bjsxt.height.design016_test;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:生产者
 *
 * @author wzz
 * @since: 1.0
 * Create Date Time: 2018/11/1 15:33
 * Update Date Time:
 */
public class Provider implements Runnable{

    //共享缓存区
    private BlockingQueue<Data> queue;
    //多线程间是否启动变量，有强制从主内存中刷新的功能。即时返回线程的状态
    private volatile boolean isRunning = true;
    //id生成器
    private static AtomicInteger count = new AtomicInteger();
    //随机数
    private static Random r = new Random();

    public Provider(BlockingQueue<Data> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        while(isRunning){
            try {
                //模拟获取数据的耗时
                Thread.sleep(r.nextInt(1000));
                int id = count.incrementAndGet();
                Data data = new Data(id,"数据"+id);
                System.out.println("当前线程:"+Thread.currentThread().getName()+",获取了数据,id为:"+id+",进行装载到公共缓存区");
                if(!queue.offer(data,2, TimeUnit.SECONDS)){
                    System.out.println("提交缓冲区失败");
                    //这里可以进行其他操作......
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stop(){
        isRunning = false;
    }
}
